const fs = require("fs");
const path = require("path");
const http = require("http");
// const logger = require("../../_unit/logs");

//声明一个变量
let mimes = {
  html: "text/html",
  css: "text/css",
  js: "text/javascript",
  png: "image/png",
  jpg: "image/jpeg",
  gif: "image/gif",
  mp4: "video/mp4",
  mp3: "audio/mpeg",
  json: "application/json",
};

const server = http.createServer((require, response) => {
  const { pathname } = new URL(require.url, "http://127.0.0.1");

  // let filePath = matchPath(pathname);
  let filePath = path.resolve(__dirname, `page${pathname}`);
  fs.readFile(filePath, (err, data) => {
    if (err) {
      response.end("文件读取失败!");
    }

    let ext = path.extname(filePath).slice(1);
    let type = mimes[ext];
    if (type) {
      //匹配到了                          text/html;charset=utf-8
      if (ext === "html") {
        response.setHeader("content-type", type + ";charset=utf-8");
      } else {
        response.setHeader("content-type", type + ";charset=utf-8");
      }
    } else {
      //没有匹配到
      response.setHeader("content-type", "application/octet-stream");
    }
    // response.setHeader("Content-Type", "text/html; charset=utf-8");
    // response.setHeader("content-type", "text/javascript;charset=utf-8");

    response.end(data);
    return;
  });
});

server.listen(9000, () => {
  console.log("开启9000服务!");
});

function matchPath(pathname) {
  let filePath = "";

  /* if (pathname == "/index.html") {
    filePath = path.resolve(__dirname, "page/index.html");
    return filePath;
  }

  if (pathname == "/css/app.css") {
    filePath = path.resolve(__dirname, "page/css/app.css");
    return filePath;
  }

  if (pathname == "/images/logo.png") {
    filePath = path.resolve(__dirname, "page/images/logo.png");
    return filePath;
  } */
}
